<template>
  <div v-loading="loading" class="page-wrapper">
    <c-card title="角色列表" class="role-list">
      <div class="row">
        <c-search
          v-model="searchText"
          :height="30"
          :width="200"
          placeholder="角色名搜索"
          class="item"
          @submit="_getRoleList"
        />
        <el-button size="small" type="primary" class="item" @click="showAddDlg">添加</el-button>
      </div>
      <el-table ref="table" :data="roleList" stripe style="width: 100%" height="498">
        <el-table-column prop="rolename" label="角色名"></el-table-column>
        <el-table-column prop="rolecode" label="角色编码"></el-table-column>
        <el-table-column prop="memo" label="备注"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button size="small" type="text" @click="showEditDlg(row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteRole(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getRoleList"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg :title="(role.roleid ? '编辑' : '添加') + '角色'" :visible.sync="dialogVisible">
      <el-form
        ref="form"
        :rules="rules"
        :model="role"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="角色名称" prop="rolename">
              <el-input v-model="role.rolename" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="角色编码" prop="rolecode">
              <el-input v-model="role.rolecode" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="role.memo" type="textarea" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <el-transfer
          v-model="priList"
          :titles="['权限列表', '已选']"
          :props="{key: 'rightid',label: 'rightname'}"
          :data="privilegeList || []"
        ></el-transfer>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="submitForm">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CDlg from "@/components/CDlg";
import CSearch from "@/components/CSearch";
import { clone } from "lodash";
import { giveRgight, editRoles, getRoleRights } from "@/api/user";
import { calcPageNum } from "@/utils";
export default {
  name: "UserRole",
  components: {
    CCard,
    CDlg,
    CSearch
  },
  data() {
    return {
      loading: false,
      searchText: "",
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      roleList: [],
      role: {},
      privilegeList: null,
      privilegeName: "",
      priList: [],
      rules: {
        rolename: [
          { required: true, message: "请输入角色名", trigger: "blur" }
        ],
        rolecode: [
          { required: true, message: "请输入角色编码", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);
    this.loading = true;
    this._getRoleList().finally(() => (this.loading = false));
  },
  methods: {
    _getRoleList() {
      const params = {
        roleName: this.searchText || "",
        page: this.page.index,
        rows: this.page.size
      };
      return this.$axios
        .get("plat/user/queryRoles", { params })
        .then(res => {
          if (res.code === 1) {
            this.roleList = res.data.rows;
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    getPrivilegeList() {
      const params = {
        rightName: this.privilegeName || "",
        page: 1,
        rows: 1000
      };
      return this.$axios
        .get("plat/user/queryRights", { params })
        .then(res => {
          if (res.code === 1) {
            this.privilegeList = res.data.rows;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    showAddDlg() {
      if (!this.privilegeList) {
        this.getPrivilegeList();
      }
      this.dialogVisible = true;
      if (this.role.roleid) {
        this.priList = [];
        this.role = {};
        this.privilegeName = "";
      }
    },
    showEditDlg(r) {
      if (!this.privilegeList) {
        this.getPrivilegeList();
      }
      this.dialogVisible = true;
      if (this.role.roleid !== r.roleid) {
        this.role = clone(r);
        this.privilegeName = "";
        getRoleRights(r.roleid).then(data => {
          if (data.length === 0) this.priList = [];
          else {
            const rights = data[0].rights;
            this.priList = rights.map(e => e.rightid);
          }
        });
      }
    },
    deleteRole(r) {
      this.$confirm(`此操作将永久删除角色<${r.rolename}>, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const load = this.$loading();
        return this.$axios
          .delete("plat/user/deleteRoles", { params: { roleIds: r.roleid } })
          .then(res => {
            if (res.code === 1) {
              this._getRoleList();
            } else {
              throw res.msg;
            }
          })
          .catch(e => this.$message.error(e))
          .finally(() => {
            load.close();
          });
      });
    },
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          const load = this.$loading();
          try {
            const data = await editRoles(this.role);
            this._getRoleList();
            await giveRgight(data.roleid, this.priList);
            this.role = {};
            this.priList = [];
            this.dialogVisible = false;
            load.close();
          } catch (e) {
            load.close();
            this.$message.error(e);
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.role-list {
  text-align: left;
}
</style>
